﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.media;
using UmbSearch2.Search;
using System.Collections;
using umbraco.BusinessLogic;
using umbraco.presentation.nodeFactory;

namespace UmbSearch2.UserControls
{
	public partial class SearchResult : System.Web.UI.UserControl
	{
		// private variables
		private string[] searchFields;
		private ArrayList documentTypes = new ArrayList();
		private bool isMediaNode;
		private bool isDocumentNode;
		private List<SearchResultItem> results = new List<SearchResultItem>();
		private string query;
		private int currentPage = 1;
		private int numberOfSearchResultItemsPerPage;

        // properties that can be set in Umbraco
		public int SearchStartNodeId { get; set; }

		public object DocumentTypes
		{
			set
			{
				string[] temp = value.ToString().Split(',');
				for (int i = 0; i < temp.Length; i++)
				{
					documentTypes.Add(temp[i].Trim());
				}
			}
		}

		public object SearchFields
		{
			set
			{
				searchFields = value.ToString().Split(',');
			}
		}

		public int NumberOfSearchResultItemsPerPage 
		{ 
			get
			{
				if (numberOfSearchResultItemsPerPage != 0)
					return numberOfSearchResultItemsPerPage;
				return 10;
			}
			set
			{
				numberOfSearchResultItemsPerPage = value;
			}
		}
		public bool PagingOnTop { get; set; }
		public bool PagingOnBottum { get; set; }
		public int MisspelledWordsNodeId { get; set; }
		
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!string.IsNullOrEmpty(Request.QueryString["query"]))
			{
				query = Request.QueryString["query"];

				// get all the results
				results = Searcher.Search(query, searchFields, SearchStartNodeId, MisspelledWordsNodeId, documentTypes);
			}

			if (!string.IsNullOrEmpty(Request.QueryString["page"]))
			{
				currentPage = int.Parse(Request.QueryString["page"]);
			}

			Initialize();
		}

		private void Initialize()
		{
			try
			{
				if (results != null && results.Count > 0)
				{
					// only then we need paging ...
					if (results.Count > numberOfSearchResultItemsPerPage){
						
						// add paging
						if (PagingOnTop)
						{
							PlaceHolderPagingTop.Visible = true;
							PlaceHolderPagingTop.Controls.Add(CreatePager());
							PlaceHolderPagingTop.Controls.Add(new LiteralControl("<br/>"));
							PlaceHolderPagingTop.Controls.Add(new LiteralControl("<br/>"));
						}

						if (PagingOnBottum)
						{
							PlaceHolderPagingBottum.Visible = true;
							PlaceHolderPagingBottum.Controls.Add(CreatePager());
						}
					}

					if (results.Count == 1)
					{
						ltlMessage.Text = string.Format(Resources.UmbSearch2Resources.Succes1Result, query);
					}
					else
					{
						//"Your query for '" + query + "' resulted in " + results.Count + " hit(s)."
						ltlMessage.Text = string.Format(Resources.UmbSearch2Resources.Succes, query, results.Count);
					}

					ShowResults(results);
				}
				else
				{
					//"Your query for '" + query + "' didn't yield any results."
					ltlMessage.Text = string.Format(Resources.UmbSearch2Resources.Failure, query);
				}
			}
			catch (Exception ex)
			{
				Log.Add(LogTypes.Error,User.GetUser(0),Node.GetCurrent().Id,ex.Message);
			}
		}

		private Pager CreatePager()
		{
			Pager pager = (Pager) LoadControl("Pager.ascx");
			pager.CurrentPage = currentPage;
			pager.TotalResults = results.Count;
			pager.NumberOfSearchResultItemsPerPage = numberOfSearchResultItemsPerPage;
			return pager;
		}

		private void ShowResults(List<SearchResultItem> results)
		{
			// take selection of the results
			results = results.Skip((currentPage - 1) * NumberOfSearchResultItemsPerPage).Take(numberOfSearchResultItemsPerPage).ToList();

			// create <li> .. </li>
			foreach (var result in results)
			{
				CheckNodeType(result);
				CreateSearchResultItem(result);
			}
		}

		private void CreateSearchResultItem(SearchResultItem resultItem)
		{
			plhSearchResults.Controls.Add(new LiteralControl("<li>"));

			SearchResultTemplate result = (SearchResultTemplate)LoadControl("SearchResultTemplate.ascx");
			result.Hyperlink = CreateHyperlink(resultItem);
			result.Summary = resultItem.Summary;
			result.Match = resultItem.Match;
			plhSearchResults.Controls.Add(result);

			plhSearchResults.Controls.Add(new LiteralControl("</li>"));
		}

		private void CheckNodeType(SearchResultItem resultItem)
		{
			if (resultItem.ObjectType == Media._objectType)
			{
				isMediaNode = true;
				isDocumentNode = false;
			}

			if (resultItem.ObjectType == umbraco.cms.businesslogic.web.Document._objectType)
			{
				isMediaNode = false;
				isDocumentNode = true;
			}
		}

		private HyperLink CreateHyperlink(SearchResultItem resultItem)
		{
			HyperLink link = new HyperLink();

			if (isDocumentNode)
			{
				link.Text = resultItem.Title;
				link.NavigateUrl = umbraco.library.NiceUrl(resultItem.Id);
			}
			if (isMediaNode)
			{
				link.Text = resultItem.Title + "." + resultItem.Extension;
				link.NavigateUrl = resultItem.FilePath;
				link.Target = "_blank";
			}

			return link;
		}
	}
}